package com.library;

import java.sql.*;
import java.util.Properties;

public class DBConnection {
    private static final String URL = "jdbc:mysql://localhost:3306/library_management_system";
    private static final String USERNAME = "library_user";
    private static final String PASSWORD = "library_password";

    private static Connection connection = null;

    static {
        try {
            // 加载MySQL驱动
            Class.forName("com.mysql.cj.jdbc.Driver");
        } catch (ClassNotFoundException e) {
            System.err.println("MySQL驱动加载失败: " + e.getMessage());
        }
    }

    public static Connection getConnection() {
        try {
            if (connection == null || connection.isClosed()) {
                Properties props = new Properties();
                props.setProperty("user", USERNAME);
                props.setProperty("password", PASSWORD);
                props.setProperty("useUnicode", "true");
                props.setProperty("characterEncoding", "utf8");
                props.setProperty("serverTimezone", "Asia/Shanghai");
                props.setProperty("useSSL", "false");

                connection = DriverManager.getConnection(URL, props);
            }
            return connection;
        } catch (SQLException e) {
            System.err.println("数据库连接失败: " + e.getMessage());
            return null;
        }
    }

    public static void closeConnection() {
        if (connection != null) {
            try {
                connection.close();
                connection = null;
            } catch (SQLException e) {
                System.err.println("关闭数据库连接失败: " + e.getMessage());
            }
        }
    }

    public static void closeResources(Connection conn, Statement stmt, ResultSet rs) {
        try {
            if (rs != null) rs.close();
            if (stmt != null) stmt.close();
            if (conn != null && conn != connection) conn.close(); // 不关闭静态连接
        } catch (SQLException e) {
            System.err.println("关闭数据库资源失败: " + e.getMessage());
        }
    }

    public static void closeResources(Connection conn, Statement stmt) {
        closeResources(conn, stmt, null);
    }
}